﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using PolePositionMobileUtilityEntity;
using PolePositionMobileUtilityEntity.Entities;
using PolePositionMobileUtilityEntity.Logic;
using PolePositionMobileUtilityGeneral;
using PolePositionMobileUtilityLogic;

namespace PolePositionMobileUtilityApplication
{
    public partial class frmUtility : frmBase
    {
        private List<Int32> _ValuesSpecie;
        private List<Int32> _ValuesClass;
        private List<Int32> _ValuesTreatment;
        private List<Int32> _ValuesLength;
        private List<Int32> _ValuesToptype;
        private List<Int32> _ValuesInspector;
        private List<Int32> _ValuesCompany;
        private List<Int32> _ValuesYear;
        private List<Int32> _ValuesInspectionType;
        private List<Int32> _ValuesResultType;
        private List<Int32> _ValuesVisitTypes;
        private Int32 m_InspectionId;
        private EUtilityInspectionResult m_InspectionResult;
        private bool m_IsDuplication;
        private ESetting m_Settings;

        public void SetIsDuplication(bool value)
        {
            m_IsDuplication = value;
        }

        public frmUtility()
        {
            SendToBack();

            InitializeComponent();
            LoadCombos();
            CleanValues();
            InitilizeControls();
        }

        private void InitilizeControls()
        {
            ctrlPosition.Gps = m_GPS;
        }

        private void frmUtilityEditor_Load(object sender, EventArgs e)
        {
            try
            {
                ctrlPosition.RefreshPosition();
                SetButtonLRProperties();
                SetTitle("PPI | Inspection Process");
                InitializeInspection();
            }
            catch (Exception ex)
            {

                throw;
            }

        }

        private void LoadCombos()
        {
            EClass c = new EClass();
            EClass[] cArray = c.GetAll();
            _ValuesClass = MobileUIHelper.FillDropdown(ddlClass, cArray, "Name", "Id", "[Class]");

            ECompany co = new ECompany();
            ECompany[] coArray = co.GetAll();
            _ValuesCompany = MobileUIHelper.FillDropdown(ddlCompany, coArray, "Name", "Id", "[Company]");

            EInspector i = new EInspector();
            EInspector[] iArray = i.GetAll();
            _ValuesInspector = MobileUIHelper.FillDropdown(ddlInspector, iArray, "Name", "Id", "[Inspector]");

            ELength l = new ELength();
            ELength[] lArray = l.GetAll();
            _ValuesLength = MobileUIHelper.FillDropdown(ddlLength, lArray, "Name", "Id", "[Length]");


            ESpecie e = new ESpecie();
            ESpecie[] eArray = e.GetAll();
            _ValuesSpecie = MobileUIHelper.FillDropdown(ddlSpecie, eArray, "Name", "Id", "[Species]");

            EToptype t = new EToptype();
            EToptype[] tArray = t.GetAll();
            _ValuesToptype = MobileUIHelper.FillDropdown(ddlToptype, tArray, "Name", "Id", "[Toptype]");

            ETreatment tr = new ETreatment();
            ETreatment[] trArray = tr.GetAll();
            _ValuesTreatment = MobileUIHelper.FillDropdown(ddlTreatment, trArray, "Name", "Id", "[Treat]");

            EInspectionType it = new EInspectionType();
            EInspectionType[] itArray = it.GetAll();
            _ValuesInspectionType = MobileUIHelper.FillDropdown(ddlInspection, itArray, "Name", "Id", "[Inspection]");

            EResultType ret = new EResultType();
            EResultType[] retArray = ret.GetAll();
            _ValuesResultType = MobileUIHelper.FillDropdown(ddlResult, retArray, "Name", "Id", "[Result]");

            EVisitType visitType = new EVisitType();
            EVisitType[] visitTypeArray = visitType.GetAll();
            _ValuesVisitTypes = MobileUIHelper.FillDropdown(ddlVisitType, visitTypeArray, "Name", "Id", "[VisitType]");

            _ValuesYear = MobileUIHelper.FillDropdownYears(ddlYear, 1944, DateTime.Now.Year, "[Year]");

            MobileUIHelper.FillNumericCombo(ddlGuardsQuantity, 1, 8, 1, true, "[Quantity]");
            MobileUIHelper.FillNumericCombo(ddlLastVisit, DateTime.Now.Year, DateTime.Now.Year - 100, 1, false, string.Empty);

            ddlMap.LoadDropDowns();
            lstNotes.LoadCombos();
        }

        private void LoadDefaultValues()
        {
            m_Settings = LSetting.GetAll();
            MobileUIHelper.SetSelectedValue(_ValuesInspector, m_Settings.Inspector.Id, ddlInspector);
            MobileUIHelper.SetSelectedValue(_ValuesCompany, m_Settings.Company.Id, ddlCompany);
            ddlInspector.Enabled = false;
            ddlCompany.Enabled = false;
        }

        private void InitializeInspection()
        {
            CleanValues();
            if (m_InspectionId != Int32.MinValue)
            {
                m_InspectionResult = LUtilityInspectionResult.GetById(m_InspectionId);
                LoadDefaultValues();
                LoadData();                
                if (m_IsDuplication)
                {
                    m_InspectionResult.Inspection.Images.Clear();
                    ctrlCamera.Clean();
                    ddlResult.SelectedIndex = 0;
                }
            }
            else
            {
                m_InspectionResult = new EUtilityInspectionResult();
                m_InspectionId = Int32.MinValue;
                CleanValues();
                LoadDefaultValues();
            }
        }

        private void LoadData()
        {
            MobileUIHelper.SetSelectedValue(_ValuesInspector, m_InspectionResult.Inspection.Inspector.Id, ddlInspector);
            MobileUIHelper.SetSelectedValue(_ValuesCompany, m_InspectionResult.Inspection.Company.Id, ddlCompany);
            MobileUIHelper.SetSelectedValue(_ValuesClass, m_InspectionResult.Inspection.Class.Id, ddlClass);
            MobileUIHelper.SetSelectedValue(_ValuesLength, m_InspectionResult.Inspection.Length.Id, ddlLength);
            MobileUIHelper.SetSelectedValue(_ValuesSpecie, m_InspectionResult.Inspection.Specie.Id, ddlSpecie);
            MobileUIHelper.SetSelectedValue(_ValuesToptype, m_InspectionResult.Inspection.Toptype.Id, ddlToptype);
            MobileUIHelper.SetSelectedValue(_ValuesTreatment, m_InspectionResult.Inspection.Treatment.Id, ddlTreatment);
            MobileUIHelper.SetSelectedValue(_ValuesYear, m_InspectionResult.Inspection.Year, ddlYear);
            MobileUIHelper.SetSelectedValue(_ValuesInspectionType, m_InspectionResult.InspectionType.Id, ddlInspection);
            MobileUIHelper.SetSelectedValue(_ValuesResultType, m_InspectionResult.ResultType.Id, ddlResult);
            MobileUIHelper.SetSelectedValue(_ValuesVisitTypes, m_InspectionResult.Inspection.VisitType.Id, ddlVisitType);
            
            dLVisit.Value = m_InspectionResult.Inspection.LVisit;
            txtNumber.Text = m_InspectionResult.Inspection.Number;
            chkElectrical.Checked = m_InspectionResult.IsElectrical;
            lstNotes.SetSelectedValues(m_InspectionResult.Notes);
            ddlMap.SetMapValue(m_InspectionResult.Inspection.Map.Id);
            ddlMap.SetSectionValue(m_InspectionResult.Inspection.Section.Id);
            ctrlCamera.SetTakenImages(m_InspectionResult.Inspection.Images);
            ctrlPosition.SetPosition(m_InspectionResult.Inspection.Latitude, m_InspectionResult.Inspection.Longitude);
            txtComments.Text = m_InspectionResult.Comments;
            txtLastCompany.Text = m_InspectionResult.Inspection.LastCompany;
            ddlLastVisit.SelectedItem = m_InspectionResult.Inspection.LVisit.Year;

            if (m_InspectionResult.Inspection.GuardsQuantity == int.MinValue || m_InspectionResult.Inspection.GuardsQuantity == 0)
            {
                ddlGuardsQuantity.SelectedIndex = 0;
                chkGuards.Checked = false;
            }
            else
            {
                ddlGuardsQuantity.SelectedItem = m_InspectionResult.Inspection.GuardsQuantity;
                chkGuards.Checked = true;
            }

            chkPoleTagId.Checked = m_InspectionResult.Inspection.PoleTag;
            chkGWRepair.Checked = m_InspectionResult.Inspection.GroundWireRepair;
            chkBillable.Checked = m_InspectionResult.Inspection.Billable;
        }

        private void SetButtonLRProperties()
        {
            SetRButton("Cancel");
            SetLButton("Next");
        }

        public void SetInspection(int inspectionId)
        {
            m_InspectionId = inspectionId;
        }

        private void CleanValues()
        {
            dLVisit.Value = DateTime.Now;
            txtNumber.Text = string.Empty;
            txtComments.Text = string.Empty;
            txtLastCompany.Text = string.Empty;
            ddlMap.Clean();
            lstNotes.Clean();
            ctrlCamera.Clean();
            ddlInspection.SelectedIndex = 0;
            ddlClass.SelectedIndex = 0;
            ddlCompany.SelectedIndex = 0;
            ddlInspector.SelectedIndex = 0;
            ddlLength.SelectedIndex = 0;
            ddlResult.SelectedIndex = 0;
            ddlVisitType.SelectedIndex = 0;
            ddlSpecie.SelectedIndex = 0;
            ddlToptype.SelectedIndex = 0;
            ddlTreatment.SelectedIndex = 0;
            ddlGuardsQuantity.SelectedIndex = 0;
            ddlYear.SelectedIndex = 0;
            ddlLastVisit.SelectedIndex = 0;
            chkElectrical.Checked = false;
            chkGuards.Checked = false;
            ddlGuardsQuantity.Enabled = false;
            chkBillable.Checked = false;
            chkGWRepair.Checked = false;
            chkPoleTagId.Checked = false;
        }

        protected override void lblClose_Click(object sender, EventArgs e)
        {
            ctrlCamera.DisableCamera();
            Close();
        }

        protected override void lblRButton_Click(object sender, EventArgs e)
        {
            ctrlCamera.DisableCamera();
            Close();
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedIndex)
            {
                case 0:
                    ctrlCamera.DisableCamera();
                    SetLButton("Next");
                    break;
                case 1:
                    ctrlCamera.DisableCamera();
                    SetLButton("Next");
                    break;
                case 2:
                    ctrlCamera.DisableCamera();
                    SetLButton("Save");
                    break;
                case 3:
                    SetLButton("Save");
                    ctrlCamera.ActiveCamera();
                    break;
                default:
                    break;
            }
        }

        public void SetSelectedTab(ResultTabs tab)
        {
            tabControl1.SelectedIndex = (Int32)tab;
        }

        protected override void lblLButton_Click(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedIndex)
            {
                case 0:
                    tabControl1.SelectedIndex = 1;
                    break;
                case 1:
                    tabControl1.SelectedIndex = 2;
                    break;
                case 2:
                    if (ValidateData())
                    {
                        SaveInspectionResult();
                        ctrlCamera.DisableCamera();
                        Close();
                    }
                    break;
                case 3:
                    if (ValidateData())
                    {
                        SaveInspectionResult();
                        ctrlCamera.DisableCamera();
                        Close();
                    }
                    break;
                default:
                    break;
            }
        }

        private bool ValidateData()
        {
            bool _isValidResult = false;
            bool _isValidInspectionType = false;
            bool _isValid;
            bool _isValidNotes = false;
            bool _isValidCompany = false;
            bool _isValidInspector = false;
            bool _isValidMap = false;
            bool _isValidSection = false;
            StringBuilder _errorMessage = new StringBuilder();

            if (MobileUIHelper.GetSelectedValue(_ValuesResultType, ddlResult) != Int32.MinValue)
            {
                int resultType = EResultType.parseValue(ddlResult.Text);
                if (resultType >= 30)
                {
                    if (ctrlCamera.GetTakenImages().Count >= 1)
                    {
                        _isValidResult = true;
                    }
                    else
                    {
                        _errorMessage.AppendLine("The selected " + ddlResult.Text + " requires at least 1 image.");
                    }
                    if (lstNotes.GetSelectedValues().Count >= 1)
                    {
                        _isValidNotes = true;
                    }
                    else
                    {
                        _errorMessage.AppendLine("The selected " + ddlResult.Text + " requires at least 1 note.");
                    }
                }
                else
                {
                    _isValidResult = true;
                    _isValidNotes = true;
                }
            }
            else
            {
                _errorMessage.AppendLine("Result Type is Required");
            }

            if (MobileUIHelper.GetSelectedValue(_ValuesInspectionType, ddlInspection) != Int32.MinValue)
            {
                _isValidInspectionType = true;
            }
            else
            {
                _errorMessage.AppendLine("Inspection Type is Required");
            }

            if (MobileUIHelper.GetSelectedValue(_ValuesInspector, ddlInspector) != Int32.MinValue)
            {
                _isValidInspector = true;
            }else
            {
                _errorMessage.AppendLine("Inspector is Required.");
            }
            if (MobileUIHelper.GetSelectedValue(_ValuesCompany, ddlCompany) != Int32.MinValue)
            {
                _isValidCompany = true;
            }
            else
            {
                _errorMessage.AppendLine("Company is Required.");
            }

            if (ddlMap.GetMapValue() != Int32.MinValue)
            {
                _isValidMap = true;

            }
            else
            {
                _errorMessage.AppendLine("Map is Required.");
            }

            if(ddlMap.GetSectionValue() != Int32.MinValue)
            {
                _isValidSection = true;
                
            }else
            {
                _errorMessage.AppendLine("Section is Required.");

            }

            _isValid = (_isValidResult && _isValidInspectionType && _isValidNotes && _isValidInspector && _isValidCompany && _isValidMap && _isValidSection);

            if (!_isValid)
            {
                if(ctrlCamera.IsPowerOn())
                {
                    ctrlCamera.DisableCamera();
                    MessageBox.Show(_errorMessage.ToString(), "Validation");
                    ctrlCamera.ActiveCamera();
                }else
                    MessageBox.Show(_errorMessage.ToString(), "Validation");
            }

            return _isValid;
        }

        private void SaveInspectionResult()
        {
            EUtilityInspectionResult _result = new EUtilityInspectionResult();
            _result.Id = m_InspectionId;
            if (m_IsDuplication)
            {
                _result.Id = Int32.MinValue;
            }

            if (_result.Id != Int32.MinValue)
            {
                _result.Inspection.Id = m_InspectionResult.Inspection.Id;
            }
            _result.InspectionType = new EInspectionType(MobileUIHelper.GetSelectedValue(_ValuesInspectionType, ddlInspection), ddlInspection.Text);
            _result.Notes = lstNotes.GetSelectedValues();
            _result.Comments = txtComments.Text;
            _result.IsElectrical = chkElectrical.Checked;
            _result.ResultType = new EResultType(MobileUIHelper.GetSelectedValue(_ValuesResultType, ddlResult), ddlResult.Text);
            _result.Inspection.VisitType = new EVisitType(MobileUIHelper.GetSelectedValue(_ValuesVisitTypes, ddlVisitType), ddlVisitType.Text);
            _result.Inspection.AcquisitionDate = DateTime.Now;
            _result.Inspection.Class = new EClass(MobileUIHelper.GetSelectedValue(_ValuesClass, ddlClass), ddlClass.Text);
            _result.Inspection.Company = new ECompany(MobileUIHelper.GetSelectedValue(_ValuesCompany, ddlCompany), ddlCompany.Text);
            _result.Inspection.Inspector = new EInspector(MobileUIHelper.GetSelectedValue(_ValuesInspector, ddlInspector), ddlInspector.Text);

            if (ddlGuardsQuantity.SelectedIndex > 0)
                _result.Inspection.GuardsQuantity = (int)ddlGuardsQuantity.SelectedItem;
            else
                _result.Inspection.GuardsQuantity = Int32.MinValue;
                    

            if (ctrlPosition.HasPosition)
            {
                _result.Inspection.Latitude = ctrlPosition.Latitude;
                _result.Inspection.Longitude = ctrlPosition.Longitude;
            }
            else
            {
                _result.Inspection.Latitude = 0;
                _result.Inspection.Longitude = 0;
            }

            _result.Inspection.Length = new ELength(MobileUIHelper.GetSelectedValue(_ValuesLength, ddlLength), ddlLength.Text);
            //_result.Inspection.LVisit = dLVisit.Value;
            _result.Inspection.LVisit = new DateTime((int)ddlLastVisit.SelectedItem, 1, 1);
            _result.Inspection.Map = new EMap(ddlMap.GetMapValue(), "");
            _result.Inspection.Section = new ESection(ddlMap.GetSectionValue(), "", _result.Inspection.Map);
            _result.Inspection.Number = txtNumber.Text;
            _result.Inspection.Specie = new ESpecie(MobileUIHelper.GetSelectedValue(_ValuesSpecie, ddlSpecie), ddlSpecie.Text);
            _result.Inspection.Toptype = new EToptype(MobileUIHelper.GetSelectedValue(_ValuesToptype, ddlToptype), ddlToptype.Text);
            _result.Inspection.Treatment = new ETreatment(MobileUIHelper.GetSelectedValue(_ValuesTreatment, ddlTreatment), ddlTreatment.Text);
            _result.Inspection.Year = MobileUIHelper.GetSelectedValue(_ValuesYear, ddlYear);
            _result.Inspection.Images = ctrlCamera.GetTakenImages();
            _result.Inspection.LastCompany = txtLastCompany.Text.Trim();
            _result.Inspection.Billable = chkBillable.Checked;
            _result.Inspection.PoleTag = chkPoleTagId.Checked;
            _result.Inspection.GroundWireRepair = chkGWRepair.Checked;

            LUtilityInspectionResult.Save(_result);
        }

        private void txtNumber_GotFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = true;
        }

        private void txtNumber_LostFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = false;
        }

        private void txtComments_GotFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = true;
        }

        private void txtComments_LostFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = false;
        }

        private void txtLastCompany_GotFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = true;
        }

        private void txtLastCompany_LostFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = false;
        }

        private void chkGuards_CheckStateChanged(object sender, EventArgs e)
        {
            ddlGuardsQuantity.Enabled = chkGuards.Checked;

            if (!chkGuards.Checked)
                ddlGuardsQuantity.SelectedIndex = 0;
        }
    }
}